//
//  RootViewController.m
//  MusicPlayer
//
//  Created by dllo on 15/12/19.
//  Copyright © 2015年 dllo. All rights reserved.
//

#import "RootViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Music.h"
@interface RootViewController ()

/*****  控 件  ******/
// 背景View,所有的控件都添加在它的上面
@property(nonatomic, strong)UIView *backView;
// 播放音乐
@property(nonatomic, strong)AVAudioPlayer *musicPlayer;
// 显示图片
@property(nonatomic, strong)UIImageView *headImageView;
// 记录歌曲的长度
@property(nonatomic, assign)NSInteger duration;
// 显示歌曲进度
@property(nonatomic, strong)UIProgressView *musicProgress;
// 显示歌曲倒计时
@property(nonatomic, strong)UILabel *showMusicCountDownLabel;
// 显示歌曲顺序计时
@property(nonatomic, strong)UILabel *showMusicSequenceLabel;
// 添加显示歌曲总时间的Label
@property(nonatomic, strong)UILabel *showMusicToTalTimeLabel;
// 控制图片旋转
@property(nonatomic, strong)NSTimer *rotateTimer;
// 控制进度条
@property(nonatomic, strong)NSTimer *controlProgress;
// 添加一个控制播放的Button
@property(nonatomic, strong)UIButton *startButton;
// 点击"下一首"
@property(nonatomic, strong)UIButton *nextMusic;
// 点击"上一首"
@property(nonatomic, strong)UIButton *previousMusic;

/*****  容 器  ******/
@property(nonatomic, strong)NSMutableArray *musicList;
@property(nonatomic, strong)NSMutableArray *pictureList;

/*****  变 量  ******/
@property(nonatomic, assign)NSInteger currentMusicIndex;

// 判断音乐播放器当前是否在播放
@property(nonatomic, assign)BOOL isPlay;

@end

@implementation RootViewController




- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorWithRed:86 /255.0 green:137 / 255.0 blue:158 / 255.0 alpha:1];
    
    // 读取数据
    [self createData];
    // 铺界面
    [self createView];
    
    // 添加时间控制器
    [self addTimer];
    
    // 创建音乐播放器
    [self createAVPlayer];
}
#pragma mark 创建音乐播放器
- (void)createAVPlayer{
    // 如果是第一首歌,设置上一首按钮不可点击
    if(self.currentMusicIndex == 0){
        self.previousMusic.enabled = NO;
    }
    else{
        self.previousMusic.enabled = YES;
    }
    // 如果是最后一首歌,设置下一首按钮不可点击
    if(self.currentMusicIndex == self.musicList.count - 1){
        self.nextMusic.enabled = NO;
    }
    else{
        self.nextMusic.enabled = YES;
    }
    // 停止当前音乐
    [self pauseMusic];
    // 设置进度条
    self.musicProgress.progress = 0;
    // 初始化音乐播放器
    self.musicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:self.musicList[self.currentMusicIndex] error:nil];
    // 播放音乐
    [self playMusic];
    // 设置播放状态
    self.isPlay = YES;
    // 获取歌曲的时长
    self.duration = self.musicPlayer.duration;
    // 显示歌曲总时长
    self.showMusicToTalTimeLabel.text = [NSString stringWithFormat:@"/%ld:%0.2ld",self.duration / 60, self.duration % 60];
    // 顺序显示歌曲进度
    self.showMusicSequenceLabel.text = [NSString stringWithFormat:@"%d:%0.2d",0, 0];
    // 倒序显示歌曲进度
    self.showMusicCountDownLabel.text = [NSString stringWithFormat:@"%ld:%0.2ld",self.duration / 60, self.duration % 60];;
    // 设置播放按钮
    [self.startButton setTitle:@"停止" forState:UIControlStateNormal];
}

#pragma mark 读取数据
- (void)createData{
    // 数组初始化
    self.pictureList = [NSMutableArray array];
    self.musicList = [NSMutableArray array];
    self.currentMusicIndex = 0;
    
    for(NSInteger i = 0; i < 5; i++){
        
        NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"%ld",i] ofType:@"mp3"];
        NSURL *url = [NSURL fileURLWithPath:path];
        [self.musicList addObject:url];

        // 图片
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld.jpg",i]];
        [self.pictureList addObject:image];
    }
}

#pragma mark 铺界面
- (void)createView{
    
    // 设置不透明
    self.navigationController.navigationBar.translucent = NO;
    // 设置标题
    UILabel *naTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    naTitle.text = @"音乐播放器";
    naTitle.font = [UIFont systemFontOfSize:22];
    self.navigationItem.titleView = naTitle;
    // 设置颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:86 /255.0 green:137 / 255.0 blue:158 / 255.0 alpha:1];
    
    // 添加一个backView
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(10, 10, self.view.frame.size.width - 20, self.view.frame.size.height - 84)];
    self.backView.layer.cornerRadius = 10;
    self.backView.layer.borderWidth = 1;
    self.backView.layer.masksToBounds = YES;
    self.backView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.backView];

    
    // 添加一个控制播放的Button
    self.startButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.startButton.frame = CGRectMake(165, 550, 30, 30);
    self.startButton.layer.borderWidth = 1;
    self.startButton.layer.cornerRadius = 10;
    self.startButton.layer.masksToBounds = YES;
    [self.startButton setTitle:@"停止" forState:UIControlStateNormal];
    [self.startButton addTarget:self action:@selector(startPlayMusic:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.startButton];
    
    // 添加控制播放"上一首"的Button
    self.previousMusic = [UIButton buttonWithType:UIButtonTypeSystem];
    self.previousMusic.frame = CGRectMake(60, 550, 60, 30);
    self.previousMusic.layer.borderWidth = 1;
    self.previousMusic.layer.cornerRadius = 10;
    [self.previousMusic setTitle:@"上一首" forState:UIControlStateNormal];
    [self.previousMusic addTarget:self action:@selector(previousMusic:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.previousMusic];

    // 添加控制播放"下一首"的Button
    self.nextMusic = [UIButton buttonWithType:UIButtonTypeSystem];
    self.nextMusic.frame = CGRectMake(240, 550, 60, 30);
    self.nextMusic.layer.borderWidth = 1;
    self.nextMusic.layer.cornerRadius = 10;
    [self.nextMusic setTitle:@"下一首" forState:UIControlStateNormal];
    [self.nextMusic addTarget:self action:@selector(nextMusic:) forControlEvents:UIControlEventTouchUpInside];
    [self.backView addSubview:self.nextMusic];
    
    
    // 添加一个显示"头像"的ImageView
    self.headImageView = [[UIImageView alloc] initWithFrame:CGRectMake(126, 100, 150, 150)];
    self.headImageView.image = [UIImage imageNamed:@"0.jpg"];
    self.headImageView.layer.cornerRadius = 75;
    self.headImageView.layer.borderWidth = 1;
    self.headImageView.layer.masksToBounds = YES;
    
    self.headImageView.backgroundColor = [UIColor redColor];
    [self.view addSubview:self.headImageView];
    
    // 添加歌曲进度条
    self.musicProgress = [[UIProgressView alloc] initWithFrame:CGRectMake(50, 520, 260, 100)];
    // 设置初始颜色
    self.musicProgress.trackTintColor = [UIColor redColor];
    // 设置移动后的颜色
    self.musicProgress.progressTintColor = [UIColor brownColor];
    // 设置进度条的样式
    self.musicProgress.progressViewStyle =  UIProgressViewStyleBar;
    [self.backView addSubview:self.musicProgress];
    
    // 添加显示歌曲总时间的Labe
    self.showMusicToTalTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(360, 520, 45, 20)];
    self.showMusicToTalTimeLabel.text = [NSString stringWithFormat:@"/%ld:%0.2ld",self.duration / 60, self.duration % 60];
    self.showMusicToTalTimeLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.showMusicToTalTimeLabel];
    
    // 显示歌曲时间的倒计时
    self.showMusicCountDownLabel = [[UILabel alloc] initWithFrame:CGRectMake(328, 520, 45, 20)];
    self.showMusicCountDownLabel.text = [NSString stringWithFormat:@"%ld:%0.2ld",self.duration / 60, self.duration % 60];
    self.showMusicCountDownLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.showMusicCountDownLabel];
    
    // 显示歌曲顺序计时
    self.showMusicSequenceLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 520, 45, 20)];
    self.showMusicSequenceLabel.text = [NSString stringWithFormat:@"%d:%0.2d",0, 0];
    self.showMusicSequenceLabel.font = [UIFont systemFontOfSize:14];
    [self.view addSubview:self.showMusicSequenceLabel];
}

#pragma mark 添加时间控制器
- (void)addTimer{
    
    // 设置头像旋转的时间控制器
    self.rotateTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(rotateImageView) userInfo:nil repeats:YES];
    // 暂停
    self.rotateTimer.fireDate = [NSDate distantFuture];
    
    // 控制进度条的时间控制器
    self.controlProgress = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    // 暂停
    self.controlProgress.fireDate = [NSDate distantFuture];
}
#pragma mark 时间控制器的触发方法
// 旋转头像
- (void)rotateImageView{
    // 设置图片旋转的速度为  0.01
    self.headImageView.transform = CGAffineTransformRotate(self.headImageView.transform, 0.01);
}

// 改变更新进度条
- (void)updateProgress{
    
    if(self.musicProgress.progress < 1){
        self.musicProgress.progress += (1 / ( self.duration * 1.0));
        // 设置顺序时间显示
        NSInteger musicPlayTime = self.musicProgress.progress * self.duration;
        self.showMusicSequenceLabel.text = [NSString stringWithFormat:@"%ld:%0.2ld",musicPlayTime / 60,musicPlayTime % 60];
        
        // 设置倒计时时间显示
        NSInteger countTime = self.duration - musicPlayTime;
        self.showMusicCountDownLabel.text = [NSString stringWithFormat:@"%ld:%0.2ld",countTime / 60,countTime % 60];
    }
    else{
        [self pauseMusic];
    }
}

#pragma mark 开始和暂停的Button触发方法
- (void)startPlayMusic:(UIButton *)button{
    if(button.selected == NO){
        [self pauseMusic];
        [button setTitle:@"播放" forState:UIControlStateNormal];
    }
    else{
        [self playMusic];
        [button setTitle:@"停止" forState:UIControlStateNormal];
    }
    button.selected = !button.selected;
}
#pragma mark 点击 上一首 触发的方法
- (void)previousMusic:(UIButton *)button{
    NSLog(@"上一首歌");
    self.currentMusicIndex--;
    [self createAVPlayer];
}

#pragma mark 点击 下一首 触发的方法
- (void)nextMusic:(UIButton *)button{
    NSLog(@"下一首歌");
    self.currentMusicIndex++;
    [self createAVPlayer];
}


#pragma mark 播放音乐
- (void)playMusic{
    // 播放音乐
    [self.musicPlayer play];
    // 旋转头像,启动时间控制器
    self.rotateTimer.fireDate = [NSDate distantPast];
    // 启动进度条
    self.controlProgress.fireDate = [NSDate distantPast];
}
#pragma mark 暂停音乐
- (void)pauseMusic{
    // 暂停音乐播放
    [self.musicPlayer pause];
    // 暂停旋转头像
    self.rotateTimer.fireDate = [NSDate distantFuture];
    // 暂停进度条
    self.controlProgress.fireDate = [NSDate distantFuture];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
